
class BabakanSearch extends AbstractPlugin {

  static BASE_URL = 'https://www.88mv.org';

  async fetchSearchResults(query) {
    const searchUrl = `${BabakanSearch.BASE_URL}/search/search.php?q=wd-${encodeURIComponent(query)}-pg-1`;
    const http_headers = {
      'User-Agent': BabakanSearch.DEFAULT_USER_AGENT,
      // 'Origin': BabakanSearch.BASE_URL,
    };
    const result  = await doHttpRequestSync(searchUrl, { headers: http_headers });
    if(result.status !== 'success') {
      return null;
    }
    const data = result.body;

    const parser = new DOMParser();
    const doc = parser.parseFromString(data, 'text/html');

    const searchResults = [];

    const results = doc.querySelectorAll('.index-area ul li');
    results.forEach(result => {
      const searchResult = new SearchResult();
      searchResult.site_icon = '/plugins/babakan/icon.png';
      searchResult.site_name = BabakanSearch.BASE_URL.replace(/https?:\/\/(www\.)?/, '');

      const imageElement = result.querySelector('img');
      const imageUrl = imageElement ? imageElement.getAttribute("data-original").trim() : '';
      searchResult.image = imageUrl.startsWith('/') ? `${BabakanSearch.BASE_URL}${imageUrl}` : imageUrl;
      const titleElement = result.querySelector('.link-hover');
      searchResult.title = titleElement ? titleElement.getAttribute('title').trim() : '';

      const href = titleElement ? titleElement.getAttribute('href') : '';
      searchResult.link = href.startsWith('/') ? `${BabakanSearch.BASE_URL}${href}` : href;

      const infos = [];
      result.querySelectorAll('.lzbz p:not(.name)').forEach(infoElement => {
        const info = infoElement.textContent.trim();
        if(info) {
          infos.push(info);
        }
      });
      searchResult.description = infos.join('\n');

      searchResults.push(searchResult);
    });
    return searchResults;
  }

}

Registry.registerClass("BabakanSearch", new BabakanSearch());